package com.meltingslime.asciifight.server;

import nl.chess.it.util.config.Config;
import nl.chess.it.util.config.ConfigurationException;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * @author Exit93
 * @version 1.0
 */
public class ServerConfig extends Config {

    Logger log = Logger.getLogger("asciifight.server");

    public static final String CONFIG_PATH = "asciifightserver.properties";

    public static ServerConfig create(String filePath) {
        Properties p = new Properties();
        try {
            FileInputStream f = new FileInputStream(filePath);
            p.load(f);
            f.close();
            return new ServerConfig(p);
        } catch (IOException e) {
            System.out.println("[FATAL] Cannot load config. Terminating.");
            System.exit(2);
            return null;
        }
    }

    protected ServerConfig(Properties p) throws ConfigurationException, IOException {
        super(p);
    }

    public int getPort(){
        int port = getInt("server.port");
        if (port >= 0 || port <= 65535){
            return port;
        }
        log.warn("Invalid port in config, using a random one.");
        return 0;
    }

    public int getClientCleanerInterval(){
        return getInt("server.clients.cleaner.interval");
    }

    public InetAddress getBindAddress(){
        String ipString = getString("server.address");
        if (ipString.contains(".")){
            byte[] ip = new byte[4];
            int i = 0;
            for (String num : ipString.split("\\.")){
                ip[i] = Byte.parseByte(num);
                i++;
            }
            try {
                return InetAddress.getByAddress(ip);
            } catch (UnknownHostException ignored) {}
        }
        log.warn("Invalid IP Address in config, binding on all interfaces");
        return null;
    }
}
